#include<iostream>
#include<unordered_set>
using namespace std;
const int N = 510;
int arr[N];
int n, m;
unordered_set<int>f[N];
int main()
{
	while (cin >> n) {
		for (int i = 1; i <= n; i++) {
			scanf("%d", &m);
			for (int i = 1; i <= m; i++) {
				scanf("%d", &arr[i]);
			}
			for (int i = 1; i <= m; i++) {
				for (int j = 1; j <= m; j++) {
					if (i != j) {
						f[arr[i]].insert(arr[j]);
					}
				}
			}
		}
		int q;
		cin >> q;
		while (q--) {
			int a, b;
			scanf("%d%d", &a, &b);
			int cnt = 0;
			for (int x : f[a]) {
				for (int y : f[b]) {
					if (x == y) {
						cnt++;
					}
				}
			}
			printf("%d", cnt);
		}
	}
	
	return 0;
}
//1: 2, 3, 4, 5
//2 : 1, 3, 5, 6
//4 : 1 3 5
//5 : 1 3 4 2 6
//3 : 1 2 4 5
//6 : 2 5